﻿using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.SQL;
using Wicture.EPC.Service.Benz.Models;

namespace Wicture.EPC.Service.Benz.Repository
{
    public class VinRepository : DbRESTFulRepository
    {
        private string ImageCDNUrl = ConfigurationManager.Settings.Variables["CDN.Image"];
        public object QueryVin(JToken param)
        {
            var vin = base.Invoke(CSIs.Query_Vin_By_Code, param);

            string featureList = vin.feature_list;
            var featureCodes = Enumerable.Range(0, featureList.Length / 4).Select(i => featureList.Substring(i * 4, 4));
            IEnumerable<Feature> features = base.Invoke<Feature>(CSIs.Query_Vin_Features, new { featureCodes });

            Vin result = JObject.FromObject(vin).ToObject<Vin>();

            foreach (var feature in features)
            {
                result.features.Add(new VinFeature() { code = feature.featureCode, name = feature.featureName });

                result.props.Add(new VinProperty() { name = feature.featureName, desc = feature.description });

            }
            return result;
        }

        public object QueryGroupForVin(JToken param)
        {
            var groups = base.Invoke<GroupInfo>(CSIs.List_Group_For_Vin, param);

            // TODO： Proccess img for group.

            return groups;
        }

        public object QuerySubGroupForVin(JToken param)
        {
            IEnumerable<SubGroup> subGroups = base.Invoke<SubGroup>(CSIs.Query_SubGroup, param);

            foreach (var item in subGroups)
            {
                item.image_url = $"{ImageCDNUrl}epc/mg/{item.image_url?.ToLowerInvariant()}";
                item.small_image_url = $"{ImageCDNUrl}epc/mg/small/{item.small_image_url?.ToLowerInvariant()}";
            }
            return subGroups;
        }

        public object QueryPartsForVin(JToken param)
        {
            JArray parts = JArray.FromObject(base.Invoke(CSIs.Query_Parts_For_Vin, param));

            IEnumerable<dynamic> callouts = base.Invoke(CSIs.Query_HotPoints, param);

            foreach (var part in parts)
            {
                var callout = callouts.FirstOrDefault(c => c.callout_code == part.Value<string>("callout_code"));
                part["callout_id"] = callout?.callout_id;
                part["coordinates_info"] = callout?.coordinates_info;
            }

            return parts;
        }
    }
}
